﻿using System;
using System.Net;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;

namespace MVVMFramework.Ria.Helpers
{
    internal static class ReflectionHelper
    {
        internal static Expression GetPropertyPathMemberExpression(Type entityType, ParameterExpression entityParam, string propertyPath)
        {
            Expression expression = entityParam;
            var currentType = entityType;
            if (!string.IsNullOrEmpty(propertyPath))
            {
                string[] strArray = propertyPath.Split(new char[] { '.' });
                for (int i = 0; i < strArray.Length; i++)
                {
                    var property = currentType.GetProperty(strArray[i]);
                    expression = Expression.Property(expression, property);
                    currentType = property.PropertyType;
                }
            }
            return expression;

        }

        internal static PropertyInfo GetPropertyInfo(this Type type, string propertyPath)
        {
            if (!string.IsNullOrEmpty(propertyPath))
            {
                string[] strArray = propertyPath.Split(new char[] { '.' });
                for (int i = 0; i < strArray.Length; i++)
                {
                    PropertyInfo property = type.GetProperty(strArray[i]);
                    if (property == null)
                    {
                        return null;
                    }
                    if (i == (strArray.Length - 1))
                    {
                        return property;
                    }
                    type = property.PropertyType;
                }
            }
            return null;
        }
    }
}
